package com.ship.dispatch.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SmShipFreightCost;
import com.ship.dispatch.bean.SpShipFreightAttachments;
import com.ship.dispatch.bean.boats.CreateFreightAttachmentsRq;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.bean.fob.SpFobJsfhccbItems;
import com.ship.dispatch.bpm.vo.dto.BGTableDto;
import com.ship.dispatch.mapper.SpShipFreightAttachmentsMapper;
import com.ship.dispatch.service.SpShipFreightAttachmentsService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>SpShipFreightAttachmentsServiceImpl</b>
 *
 * @description: SpShipFreightAttachmentsServiceImpl <br>
 * @date: 2024/6/11 14:46 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class SpShipFreightAttachmentsServiceImpl extends ServiceImpl<SpShipFreightAttachmentsMapper, SpShipFreightAttachments> implements SpShipFreightAttachmentsService {
    private static final Logger logger = LoggerFactory.getLogger(SpShipFreightAttachmentsServiceImpl.class);

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Override
    public void deleteFreightAttachments(List<String> ids) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("freight_id",ids);
        baseMapper.delete(queryWrapper);
    }

    @Override
    public boolean updateFreightAttachmentsById(SpShipFreightAttachments rq) {
        SpShipFreightAttachments spShipFreightAttachments = baseMapper.selectById(rq.getId());
        spShipFreightAttachments.setTitle(spShipFreightAttachments.getTitle());
        spShipFreightAttachments.setTableCell2(rq.getTableCell2());
        spShipFreightAttachments.setTableCell3(rq.getTableCell3());
        spShipFreightAttachments.setTableCell4(rq.getTableCell4());
        spShipFreightAttachments.setTableCell5(rq.getTableCell5());
        spShipFreightAttachments.setUpdateUser(SecurityUtils.getUsername());
        spShipFreightAttachments.setUpdateTime(new Date());
        int i = baseMapper.updateById(spShipFreightAttachments);
        if (i == 1){
            return true;
        }
        return false;
    }

    @Override
    public JsonResult queryFreightAttachmentsInfo(SmShipFreightCost freightCost) {
        Map<String,Object> node = new HashMap<>();
        List<SpFobJsfhccbItems> list = baseMapper.queryFreightAll(freightCost.getId());
        if (CollectionUtil.isNotEmpty(list)){
            this.getDataType(list);
        }
        List<SpFobJsfhccbItems> tables1 = list.stream().filter(item->item.getTableName().equals("CharterCost")).collect(Collectors.toList());
        tables1 = bingTableUploadRecord(tables1);
        List<SpFobJsfhccbItems> tables2 = list.stream().filter(item->item.getTableName().equals("ShippingAgencyCost")).collect(Collectors.toList());
        tables2 = bingTableUploadRecord(tables2);
        List<SpFobJsfhccbItems> tables3 = list.stream().filter(item->item.getTableName().equals("Insurance")).collect(Collectors.toList());
        tables3 = bingTableUploadRecord(tables3);
        List<SpFobJsfhccbItems> tables4 = list.stream().filter(item->item.getTableName().equals("LSMGO")).collect(Collectors.toList());
        tables4 = bingTableUploadRecord(tables4);
        List<SpFobJsfhccbItems> tables5 = list.stream().filter(item->item.getTableName().equals("VLSFO")).collect(Collectors.toList());
        tables5 = bingTableUploadRecord(tables5);
        List<SpFobJsfhccbItems> tables6 = list.stream().filter(item->item.getTableName().equals("PositioningFee")).collect(Collectors.toList());
        tables6 = bingTableUploadRecord(tables6);
        List<SpFobJsfhccbItems> tables7 = list.stream().filter(item->item.getTableName().equals("BallastBonus")).collect(Collectors.toList());
        tables7 = bingTableUploadRecord(tables7);
        List<SpFobJsfhccbItems> tables8 = list.stream().filter(item->item.getTableName().equals("BOG")).collect(Collectors.toList());
        tables8 = bingTableUploadRecord(tables8);
        List<BGTableDto> bgTableDtos = new ArrayList<>();
        BGTableDto dto = new BGTableDto();
        dto.setTableId("CharterCost");
        dto.setTableName("Charter Cost");
        dto.setTables(tables1);
        bgTableDtos.add(dto);
        dto = new BGTableDto();
        dto.setTableId("ShippingAgencyCost");
        dto.setTableName("Shipping agency cost");
        dto.setTables(tables2);
        bgTableDtos.add(dto);
        dto = new BGTableDto();
        dto.setTableId("Insurance");
        dto.setTableName("Insurance");
        dto.setTables(tables3);
        bgTableDtos.add(dto);

        dto = new BGTableDto();
        dto.setTableId("LSMGO");
        dto.setTableName("LSMGO");
        dto.setTables(tables4);
        bgTableDtos.add(dto);

        dto = new BGTableDto();
        dto.setTableId("VLSFO");
        dto.setTableName("VLSFO");
        dto.setTables(tables5);
        bgTableDtos.add(dto);


        dto = new BGTableDto();
        dto.setTableId("PositioningFee");
        dto.setTableName("Positioning fee");
        dto.setTables(tables6);
        bgTableDtos.add(dto);

        dto = new BGTableDto();
        dto.setTableId("BallastBonus");
        dto.setTableName("Ballast Bonus");
        dto.setTables(tables7);
        bgTableDtos.add(dto);

        dto = new BGTableDto();
        dto.setTableId("BOG");
        dto.setTableName("BOG");
        dto.setTables(tables8);
        bgTableDtos.add(dto);

        dto = new BGTableDto();
        String shipName = null;
        if (StringUtils.isNotEmpty(freightCost.getVoyageNumber())){
            shipName = freightCost.getVoyageNumber();
        }

        if (StringUtils.isNotEmpty(freightCost.getVesselName())){
            shipName = shipName + "-" + freightCost.getVesselName();
        }
        if (StringUtils.isNotEmpty(shipName)) {
            node.put("shipName", shipName);
        }
        String time = null;
        if (null != freightCost.getVoyageStartTime() && null != freightCost.getVoyageEndTime()){
            String startDate = DateUtil.format(freightCost.getVoyageStartTime(), DatePattern.NORM_DATETIME_FORMATTER);
            String endDate = DateUtil.format(freightCost.getVoyageEndTime(), DatePattern.NORM_DATETIME_FORMATTER);
            time = startDate + "-" + endDate;
            node.put("time",time);
        }
        node.put("data",bgTableDtos);
        node.put("type","1");
        if (StringUtils.isNotEmpty(freightCost.getVoyageNumber())){
            node.put("voyageNumber",freightCost.getVoyageNumber());
        }
        return JsonResult.success(node);
    }

    @Override
    public boolean updateFreightAttachmentsUrl(CreateFreightAttachmentsRq rq) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",rq.getId());
        updateWrapper.set("table_cell6",rq.getFileId());
        int update = baseMapper.update(null, updateWrapper);
        if (update == 1){
            return true;
        }
        return false;
    }

    @Override
    public SpShipFreightAttachments queryFreightAttachmentsById(SpShipFreightAttachments rq) {
        SpShipFreightAttachments spShipFreightAttachments = baseMapper.selectById(rq.getId());
        List<SpShipFreightAttachments> freightAttachmentsList = new ArrayList<>();
        if (null != spShipFreightAttachments){
            spShipFreightAttachments.setTableCell2(rq.getTableCell2());
            spShipFreightAttachments.setTableCell3(rq.getTableCell3());
            spShipFreightAttachments.setTableCell4(rq.getTableCell4());
            spShipFreightAttachments.setTableCell5(rq.getTableCell5());
            spShipFreightAttachments.setTableCell6(rq.getTableCell6());
        }
        return spShipFreightAttachments;
    }

    private void getDataType(List<SpFobJsfhccbItems> list) {
        list.forEach(item -> {
            item.setA1Type("text");
            item.setA2Type("number");
            if (item.getA1().replaceAll("\\u00A0","").equals("Voyagestartdate")){
                item.setA2Type("date");
            }
            if (item.getA1().replaceAll("\\u00A0","").equals("Voyageenddate")){
                item.setA2Type("date");
            }
            item.setA3Type("text");
            item.setA4Type("input");
            item.setA5Type("input");
            item.setA6Type("upload");
        });
    }

    public List<SpFobJsfhccbItems> bingTableUploadRecord( List<SpFobJsfhccbItems> table){
//        for(SpFobJsfhccbItems item:table){
//            if(item.getA6()!=null && item.getA6().length()>0){
//                String[] ids = item.getA6().split(",");
//                List<Long> resId = new ArrayList<>();
//                for(String tempId:ids){
//                    resId.add(Long.parseLong(tempId));
//                }
//                List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
//                item.setFiels(spFobFileRecordList);
//            }
//        }
        return table.stream().sorted(Comparator.comparingInt(SpFobJsfhccbItems::getOrderNo)).collect(Collectors.toList());
    }
}
